import styled from "@emotion/styled";
import {Button, TextField} from "@mui/material";
import {ChangeEvent, useState} from "react";

type IProps = {
    onConfirm: (title: string) => void;
    onCancel: () => void;
};

const CreateArea = ({onConfirm, onCancel}: IProps) => {
    const [editingTitle, setEditingTitle] = useState('');
    const [errorText, setErrorText] = useState<string | null>(null);

    const handleTitleChange = (event: ChangeEvent<HTMLInputElement>) => {
        setEditingTitle(event.target.value);
    };

    const handleConfirm = () => {
        if (editingTitle.trim() === '') {
            setErrorText('标题不能为空');
            return;
        }
        if (editingTitle.length > 64) {
            setErrorText('标题不能超过64个字符');
            return;
        }

        onConfirm(editingTitle);
        setEditingTitle('');
        setErrorText(null);

    };

    return (
        <FormArea
            onSubmit={(event) => {
                event.preventDefault(); // 阻止默认提交事件
                handleConfirm();
            }}
        >
            <TextField
                autoFocus
                label="标题"
                variant="outlined"
                value={editingTitle}
                onChange={handleTitleChange}
                error={!!errorText}
                helperText={errorText}
                slotProps={{
                    htmlInput: {
                        enterKeyHint: 'done',
                    },
                }}
            />
            <Button style={{marginLeft: '16px'}} variant="contained" onClick={handleConfirm}>确定</Button>
            <Button variant="text" onClick={onCancel}>取消</Button>
        </FormArea>
    );
};

const FormArea = styled.form`
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    margin: 16px 0;
`;

export default CreateArea;
